package com.plate.bpm.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.plate.bpm.web.model.ConsoleBean;
import com.plate.bpm.web.service.impl.ConsoleServiceImpl;
import com.plate.bpm.web.util.ManagerFlowUtil;

/**
 *作者： 李志刚
 *时间：2015年9月2日
 *流程控制台
 */
@Controller
@RequestMapping(value="console")
public class ConsoleController {
	private ProcessEngine processEngine;
	
	@Autowired
	private ConsoleServiceImpl service;
	
	/**
	 * <功能简述>流程定义列表管理
			* <功能详细描述>
			* @param request
			* @return
			* @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value="console-processDefinitionList")
	public String processList(HttpServletRequest request){
		List<ProcessDefinition> processDefinitions = processEngine.getRepositoryService()
				.createProcessDefinitionQuery().orderByProcessDefinitionId().asc().list();
		request.setAttribute("processDefinitions", processDefinitions);
		return "managerflow/managerflow";
	}
	
	/**
	 * <功能简述>根据流程定义id和流程key 获取流程全部任务节点
			* <功能详细描述>
			* @param id 流程定义id
			* @param key 流程定义key
			* @param request  
			* @return
			* @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value="console-tasklist/{id}/{key}")
	public String taskList(@PathVariable String id,@PathVariable String key,HttpServletRequest request){
		ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl)processEngine.getRepositoryService())
				.getDeployedProcessDefinition(id);
		 List<ActivityImpl> activitiList = processDefinition.getActivities();
		 Map<String,String> taskActivitylist = new HashMap<String,String>();
		 
		 for (ActivityImpl activity : activitiList) {
				if (ManagerFlowUtil.isTaskActivity(activity.getProperties().get("type").toString())) {
					taskActivitylist.put(activity.getId(), activity.getProperty("name").toString());
				}
			}
		 request.setAttribute("taskActivitylist", taskActivitylist);
		 request.setAttribute("prcDefinitionid", id);
		 request.setAttribute("prcDefinitionkey", key);
		return "managerflow/taskmanagerform";
	}
	
	/**
	 * <功能简述>获取当前处理岗位
			* <功能详细描述>
			* @param activitiId 活动节点id
			* @param processKey 流程key
			* @return bean
			* @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value="console-orgName",method=RequestMethod.POST)
	@ResponseBody
	public ConsoleBean getManagerFlowList(String activitiId, String processKey){
		ConsoleBean bean = service.getManagerFlow(activitiId, processKey);
		String groupName = null;
		if(null != bean && null != bean.getCandidate_groups() && !"".equals(bean.getCandidate_groups())){
			//获取当前岗位名称
			groupName = service.getOrgNameByRoleId(bean.getCandidate_groups());
			bean.setGroupsName(groupName);
			//TODO 获取 **未完成**
			//根据岗位获取部门名称
			bean.setOrgName("股室");
		}else{
			bean = new ConsoleBean();
		}
		return bean;
	}
	
	/**
	 * <功能简述>流程定义管理-添加/修改流程处理人
			* <功能详细描述>
			* @param managerBean
			* @param request
			* @return
			* @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value="console-save")
	public String save(ConsoleBean consoleBean,HttpServletRequest request,RedirectAttributes redirectAttributes){
		if(consoleBean !=null && null != consoleBean.getCurrGroup() && !"".equals(consoleBean.getCurrGroup())){
			//编辑
			service.update(consoleBean);
		}else{
			//添加
			service.save(consoleBean);
		}
		redirectAttributes.addAttribute("id",consoleBean.getProcess_definition_id());
		redirectAttributes.addAttribute("key",consoleBean.getProcess_definition_key());
		return "redirect:/managerflow/tasklist/{id}/{key}";
	}
	
	/**
     * 暂停流程定义.
     */
    @RequestMapping("console-pause")
    public String suspendProcessDefinition(
            @RequestParam("processDefinitionId") String processDefinitionId) {
        RepositoryService repositoryService = processEngine
                .getRepositoryService();
        repositoryService.suspendProcessDefinitionById(processDefinitionId,
                true, null);

        return "redirect:/managerflow/list";
    }

    /**
     * <功能简述>恢复流程定义
    		* <功能详细描述>
    		* @param processDefinitionId
    		* @return
    		* @see [类、类#方法、类#成员]
     */
    @RequestMapping("console-regain")
    public String activeProcessDefinition(
            @RequestParam("processDefinitionId") String processDefinitionId) {
        RepositoryService repositoryService = processEngine
                .getRepositoryService();
        repositoryService.activateProcessDefinitionById(processDefinitionId,
                true, null);

        return "redirect:/managerflow/list";
    }
    
    /**
     * <功能简述>显示流程实例列表
    		* <功能详细描述>
    		* @param request
    		* @return
    		* @see [类、类#方法、类#成员]
     */
    @RequestMapping("console-procInList")
    public String listProcessInstances(HttpServletRequest request) {
    	List<ProcessInstance> piList = service.findProcessInstances();
    	request.setAttribute("piList", piList);
        return "managerflow/pilist";
    }

    /**
     * <功能简述>删除流程实例
    		* <功能详细描述>
    		* @param processInstanceId
    		* @return
    		* @see [类、类#方法、类#成员]
     */
    @RequestMapping("console-removeProcessInstance")
    public String removeProcessInstance(
            @RequestParam("processInstanceId") String processInstanceId) {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        runtimeService.deleteProcessInstance(processInstanceId, "取消此次流程实例");

        return "redirect:/managerflow/console-piList.do";
    }

    /**
     * <功能简述>暂停流程实例
    		* <功能详细描述>
    		* @param processInstanceId
    		* @return
    		* @see [类、类#方法、类#成员]
     */
    @RequestMapping("console-suspendProcessInstance")
    public String suspendProcessInstance(
            @RequestParam("processInstanceId") String processInstanceId) {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        runtimeService.suspendProcessInstanceById(processInstanceId);

        return "redirect:/managerflow/console-piList.do";
    }

    /**
     * <功能简述>恢复流程实例
    		* <功能详细描述>
    		* @param processInstanceId
    		* @return
    		* @see [类、类#方法、类#成员]
     */
    @RequestMapping("console-activeProcessInstance")
    public String activeProcessInstance(
            @RequestParam("processInstanceId") String processInstanceId) {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        runtimeService.activateProcessInstanceById(processInstanceId);

        return "redirect:/managerflow/console-piList.do";
    }
    
	/**
	 * <功能简述>部署信息查询，部署流程定义
			* <功能详细描述>
			* @param request
			* @return
			* @see [类、类#方法、类#成员]
	 */
	@RequestMapping("console-deploylist")
	public String bushu(HttpServletRequest request){
		//部署信息管理列表  act_re_deployment 部署对象表
		List<Deployment> deployments = processEngine.getRepositoryService()
										.createDeploymentQuery()
										.orderByDeploymentId()
										.desc()
										.list();
		
		request.setAttribute("deployments", deployments);
		return "workflow/workflow";
		
	}
	
	/**
	 * @param 对processEngine进行赋值
	 */
	@Resource
	public void setProcessEngine(ProcessEngine processEngine) {
		this.processEngine = processEngine;
	}
	
}

	